package com.example.waterdispenserm2.mo.usbcong;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;

import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityUsbCongInductionCookerDisplayBinding;
import com.example.waterdispenserm2.util.MyLog;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class UsbCongInductionCookerDisplayActivity extends BasicsActivity<ActivityUsbCongInductionCookerDisplayBinding> implements UsbCongInductionCookerDisplay.DisplayCallback{
    private UsbCongInductionCookerDisplay displayController;
    private ImageView[] leds = new ImageView[8];
    private int thousands = 0, hundreds = 0, tens = 0, units = 0;
    private byte ledStatus = 0;

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    boolean isBt;
    @Override
    public void initView() {
// 初始化控制器
        displayController = new UsbCongInductionCookerDisplay(this, this);
        binding.ivMessage.setOnClickListener(v->{finish();});

        binding.connectBtn.setOnClickListener(v -> {
            isBt=true;
            if (displayController.connectToDevice()) {
                updateStatus("正在连接设备...");
            } else {
                isBt=false;
                updateStatus("连接失败");
            }
        });

        binding.disconnectBtn.setOnClickListener(v -> {
            displayController.disconnect();
            updateStatus("已断开连接");
        });

        // 按键区域
        setupKeyButtons();

        if (isBt) {
            // 初始显示
            updateDisplay();
        }
        updateStatus("准备就绪");
    }

    @Override
    protected ActivityUsbCongInductionCookerDisplayBinding getViewBinding() {
        return ActivityUsbCongInductionCookerDisplayBinding.inflate(LayoutInflater.from(this));
    }

    @SuppressLint("SetTextI18n")
    private void setupKeyButtons() {
        int[] keyButtons = {
                R.id.key_power,
                R.id.key_timer,
                R.id.key_decrease,
                R.id.key_increase,
                R.id.key_function,
                R.id.key_start
        };

        int[] keyCodes = {
                UsbCongInductionCookerDisplay.KEY_POWER,
                UsbCongInductionCookerDisplay.KEY_TIMER,
                UsbCongInductionCookerDisplay.KEY_DECREASE,
                UsbCongInductionCookerDisplay.KEY_INCREASE,
                UsbCongInductionCookerDisplay.KEY_FUNCTION,
                UsbCongInductionCookerDisplay.KEY_START
        };

        for (int i = 0; i < keyButtons.length; i++) {
            int keyCode = keyCodes[i];
            findViewById(keyButtons[i]).setOnClickListener(v -> {
                displayController.setCurrentKey(keyCode);
                binding.lastKeySent.setText("按键已设置: " + UsbCongInductionCookerDisplay.getKeyName(keyCode));
            });
        }

        // 清除按键
        binding.clearKeyBtn.setOnClickListener(v -> {
            displayController.setCurrentKey(UsbCongInductionCookerDisplay.KEY_NONE);
            binding.lastKeySent.setText("按键已清除");
        });
    }

    private void updateDisplay() {
        // 更新数码管显示
        String displayText = String.format(Locale.getDefault(),
                "%d%d%d%d", thousands, hundreds, tens, units);
        binding.displayValue.setText(displayText);

        // 更新LED显示
        updateLedDisplay();
    }

    private void updateLedDisplay() {
        // 根据LED状态更新指示灯
        int ledOnColor = ContextCompat.getColor(this, R.color.led_on);
        int ledOffColor = ContextCompat.getColor(this, R.color.led_off);

        leds[0].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_FRYING) != 0 ? ledOnColor : ledOffColor);
        leds[1].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_PORRIDGE) != 0 ? ledOnColor : ledOffColor);
        leds[2].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_HOTPOT) != 0 ? ledOnColor : ledOffColor);
        leds[3].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_HIGH_FIRE) != 0 ? ledOnColor : ledOffColor);
        leds[4].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_LOW_FIRE) != 0 ? ledOnColor : ledOffColor);
        leds[5].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_BOIL_WATER) != 0 ? ledOnColor : ledOffColor);
        leds[6].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_STEAM) != 0 ? ledOnColor : ledOffColor);
        leds[7].setColorFilter((ledStatus & UsbCongInductionCookerDisplay.LED_STEW) != 0 ? ledOnColor : ledOffColor);
    }

    private void updateStatus(String message) {
        binding.connectionStatus.setText(message);
    }

    private void appendToMonitor(String message) {
        MyLog.d("---接收--",message);
        String time = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
        String currentText = binding.dataMonitor.getText().toString();
        String newText = "[" + time + "] " + message + "\n" + currentText;

        // 限制显示行数
        if (newText.split("\n").length > 20) {
            newText = newText.substring(0, newText.lastIndexOf("\n", newText.lastIndexOf("\n") - 1));
        }

        binding.dataMonitor.setText(newText);
    }

    @Override
    public void onDisplayUpdate(int thousands, int hundreds, int tens, int units, byte ledStatus) {
        runOnUiThread(() -> {
            this.thousands = thousands;
            this.hundreds = hundreds;
            this.tens = tens;
            this.units = units;
            this.ledStatus = ledStatus;
            updateDisplay();
        });
    }

    @Override
    public void onConnectionStatusChanged(boolean connected) {
        runOnUiThread(() -> {
            if (connected) {
                binding.connectionStatus.setText("已连接设备");
                binding.connectionStatus.setTextColor(Color.GREEN);
            } else {
                binding.connectionStatus.setText("未连接");
                binding.connectionStatus.setTextColor(Color.RED);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onError(String errorMessage) {
        runOnUiThread(() -> {
            binding.connectionStatus.setText("错误: " + errorMessage);
            binding.connectionStatus.setTextColor(Color.RED);
            appendToMonitor("错误: " + errorMessage);
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onKeySent(int keyCode) {
        runOnUiThread(() -> {
            binding.lastKeySent.setText("已发送按键: " + UsbCongInductionCookerDisplay.getKeyName(keyCode));
            appendToMonitor("发送按键: " + UsbCongInductionCookerDisplay.getKeyName(keyCode));
        });
    }

    @Override
    public void onDataReceived(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder();
            sb.append("接收数据: ");
            for (byte b : data) {
                sb.append(String.format("0x%02X ", b));
            }
            appendToMonitor(sb.toString());
        });
    }

    @Override
    public void onDataSent(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder();
            sb.append("发送数据: ");
            for (byte b : data) {
                sb.append(String.format("0x%02X ", b));
            }
            appendToMonitor(sb.toString());
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (displayController != null) {
            displayController.disconnect();
        }
    }
}